package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"shop/api/request"
	"shop/initernal/dao"
	"shop/initernal/model"
)

func AddOrder(c *gin.Context) {
	var req request.AddOrder
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "取值失败",
			"data":    err.Error(),
		})
		return
	}

	context := model.Order{
		UserId: c.GetUint("userId"),
		ShopId: uint(req.ShopId),
	}
	dao.Create(&context)

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "新增订单成功",
		"data":    context,
	})

}

func QueryOrder(c *gin.Context) {

	var data []model.Order
	if !dao.GetListByFields(&model.Order{UserId: c.GetUint("userId")}, &data) {
		c.JSON(http.StatusOK, gin.H{
			"code":    0,
			"message": "查询评论失败",
			"data":    nil,
		})
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "查询评论成功",
		"data":    data,
	})
}

func UpdateOrder(c *gin.Context) {
	var req request.UpdateOrder
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "取值失败",
			"data":    err.Error(),
		})
		return
	}
	ui := c.GetUint("userId")
	var data model.Order
	if !dao.GetOneByFields(&model.Order{UserId: ui}, &data) {
		c.JSON(http.StatusOK, gin.H{
			"code":    1000,
			"message": "订单不存在",
			"data":    nil,
		})
		return
	}

	if !dao.Update(&model.Order{Id: data.Id, CType: uint(req.CType)}) {
		c.JSON(http.StatusOK, gin.H{
			"code":    1000,
			"message": "订单修改失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "订单修改成功",
		"data":    data,
	})
}

func DeleteOrder(c *gin.Context) {
	var req request.DeleteOrder
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "取值失败",
			"data":    err.Error(),
		})
		return
	}
	ui := c.GetUint("userId")
	var data model.Order
	if !dao.GetOneByFields(&model.Order{UserId: ui}, &data) {
		c.JSON(http.StatusOK, gin.H{
			"code":    1000,
			"message": "订单不存在",
			"data":    nil,
		})
		return
	}

	if !dao.Delete(&data) {
		c.JSON(http.StatusOK, gin.H{
			"code":    1000,
			"message": "订单取消失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "订单取消成功",
		"data":    nil,
	})

}
